<template>
  <div class="record">
    <Form
      ref="formRef"
      name="advanced_search"
      class="filter-forms"
      :model="formState"
      layout="inline"
      @finish="onFinish"
    >
      <Form.Item label="发布状态">
        <a-select
          ref="select"
          show-search
          placeholder="请选择"
          :value="valueState"
          :options="infoStateOption"
          style="width: 210px"
          :allow-clear="!!valueState"
          @change="showSearch"
        >
          <template #suffixIcon><img src="../../assets/images/tab_icon_dow.png" /></template>
        </a-select>
      </Form.Item>
      <Form.Item label="发布位置">
        <a-select
          ref="select"
          v-model:value="deviceValue"
          show-search
          placeholder="请选择"
          style="width: 210px"
          :allow-clear="!!deviceValue"
          @change="positionSearch"
        >
          <template #suffixIcon><img src="../../assets/images/tab_icon_dow.png" /></template>
          <a-select-option value=""> 全部 </a-select-option>
          <a-select-option v-for="(item, index) in positionOption" :key="index" :value="item.value">
            {{ item.label }}
          </a-select-option>
        </a-select>
      </Form.Item>
      <Form.Item label="发布时间" style="margin-right: 0">
        <a-range-picker
          v-model:value="formState.time"
          style="width: 286px"
          value-format="YYYY-MM-DD "
          separator="至"
          @change="selsectTime"
        >
          <template #suffixIcon><img src="../../assets/images/icon_calendar.png" /></template>
        </a-range-picker>
      </Form.Item>
      <Form.Item class="formBtn">
        <div class="search-container">
          <a-input
            v-if="identity === '8'"
            v-model:value="formState.publicName"
            :maxlength="50"
            placeholder="请输入发布名称、发布人或设备名称"
            style="width: 280px"
            @pressEnter="query"
          >
            <template #prefix>
              <i class="ifont-wid-icon_search" style="color: #c2c2c2"></i>
            </template>
          </a-input>
          <a-input
            v-else
            v-model:value="formState.publicName"
            :maxlength="50"
            placeholder="请输入发布名称或设备名称"
            style="width: 280px"
            @pressEnter="query"
          >
            <template #prefix>
              <i class="ifont-wid-icon_search" style="color: #c2c2c2"></i>
            </template>
          </a-input>
          <a-button type="primary" class="btn ml-4" style="width: 64px" @click="query"
            >查询</a-button
          >
          <a-button class="ml-2" style="width: 64px; color: #999999" @click="resetForm">
            重置
          </a-button>
        </div>
      </Form.Item>
    </Form>
    <div class="search-result-list" :class="tablData.length < 10 ? 'tabel-hight' : null">
      <a-table
        v-if="tablData.length !== 0"
        class="custom-table"
        style="table-layout: none"
        :columns="columns"
        :data-source="tablData"
        :pagination="false"
        :custom-row="tableRowClick"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'releaseUserName'">
            {{ record.releaseUserName || '--' }}
          </template>
          <template v-if="column.key === 'createTime'">
            {{ getFormattedPublishTime(record.createTime) }}
          </template>
          <template v-if="column.key === 'infoState'">
            <div v-if="record.infoState === 1"><div class="circle2"></div>发布中</div>
            <div v-if="record.infoState === 2"><div class="circle"></div>待生效</div>
            <div v-if="record.infoState === 3"><div class="circle4"></div>已结束</div>
            <div v-if="record.infoState === 4"><div class="circle4"></div>已撤回</div>
            <div v-if="record.infoState === 5"><div class="circle4"></div>已删除</div>
          </template>
          <template v-if="column.key === 'operation'">
            <a-button size="small" class="see" @click="toPath(record.id)">查看</a-button>
          </template>
        </template>
      </a-table>
    </div>

    <div class="loadingss">
      <Empty v-if="tablData.length === 0 && loading === false" :image="simpleImage" />
    </div>
    <div v-if="loading" class="loadings">
      <Spin class="" tip="加载中..."></Spin>
    </div>
    <div v-if="isShowPagination" class="pagination">
      <span style="color: #999999; margin-right: 8px">共{{ total }}条</span>
      <a-pagination
        v-model:current="current"
        v-model:pageSize="pageSize"
        :page-size-options="pageSizeOptions"
        show-quick-jumper
        :show-size-changer="true"
        :total="total"
        @change="onChange"
      />
    </div>
  </div>
</template>
<script>
export default {
  name: 'RecordList'
};
</script>
<script setup>
import { reactive, ref, onMounted, computed, onActivated, onDeactivated } from 'vue';
import { Form, Row, Col, Spin, Empty } from 'ant-design-vue';
import { useRouter, useRoute } from 'vue-router';
import { getReleaseRecord, equipmentType } from '@/api/user';
import { getFormattedPublishTime } from '@/util/formatDate';

const router = useRouter();
import { useStore } from 'vuex';
const store = useStore();

// 列表页数大于1时才显示分页
const isShowPagination = computed(() => Math.ceil(total.value / pageSize.value) > 1);
// 点击表格行事件
function tableRowClick(record) {
  return {
    onClick: () => {
      toPath(record.id);
    }
  };
}
const formRef = ref();
const formState = reactive({
  publicName: '', // 发布人名称检索
  infoState: '', // 发布状态什么也不传全返
  time: [],
  startDate: '', // 开始时间
  endDate: '', // 结束时间
  infoType: '', // 类型
  isDraft: 0
});
const valueState = ref(''); // 发布状态
const deviceValue = ref('');
const valuePosition = ref(undefined); // 设备类型
const pageNum = ref(1);
const pageSize = ref(10);
const total = ref(0);
let loading = ref();
let tablData = ref([]);
const simpleImage = ref(require('@/assets/images/noData@2x.png'));
const pageSizeOptions = ref(['10', '20', '30']);
function ReleaseRecord(parmas) {
  parmas.data.identity = localStorage.getItem('identity');
  loading.value = true;
  setTimeout(() => {
    getReleaseRecord(parmas)
      .then(res => {
        let { records = [], total: totalNum = 0 } = res.data?.data || {};
        // 防止最后一页只有一条删除撤回数据为空的情况
        if (records.length === 0 && totalNum > 0) {
          parmas.current--;
          current.value--;
          ReleaseRecord(parmas);
          return;
        }
        tablData.value = records;
        total.value = totalNum;
        loading.value = false;
      })
      .catch(err => {
        console.log(err);
        loading.value = false;
      });
  }, 200);
}
function toPath(id) {
  router.push({
    path: '/article-details',
    query: {
      id: id
    }
  });
}
function selsectTime(date, dateString) {
  pageNum.value = 1;
  current.value = 1;
  formState.startDate = dateString[0] ? dateString[0] + ' 00:00:00' : '';
  formState.endDate = dateString[1] ? dateString[1] + ' 23:59:59' : '';

  onFinish();
}
const onFinish = values => {
  let parmas = {
    data: {
      publicName: formState.publicName.replace(/\s*/g, ''),
      infoState: formState.infoState,
      beginTime: formState.startDate,
      finishTime: formState.endDate,
      infoType: formState.infoType,
      isDraft: formState.isDraft,
      equipmentTypeId: valuePosition.value
    },
    current: pageNum.value,
    size: pageSize.value
  };
  ReleaseRecord(parmas);
};
let identity = ref();

// 页面被激活时
const isFirstLoadPage = ref(true);
onActivated(() => {
  // console.log('onActivated');
  if (!isFirstLoadPage.value) {
    onFinish();
  }
});
onDeactivated(() => {
  isFirstLoadPage.value = false;
});

onMounted(() => {
  console.log('onMounted');
  identity.value = localStorage.getItem('identity');
  equipmentType().then(res => {
    let data = [];
    res.data.data.forEach(item => {
      data.push({
        value: item.equipmentTypeId,
        label: item.equipmentTypeName
      });
    });
    positionOption.value = data;
  });
  onFinish();
});
const positionOption = ref([]); // 位置数据
const infoStateOption = ref([
  {
    value: '',
    label: '全部'
  },
  // {
  //   value: 1,
  //   label: '发布中'
  // },
  // {
  //   value: 2,
  //   label: '待生效'
  // },
  {
    value: 3,
    label: '已结束'
  },
  {
    value: 4,
    label: '已撤回'
  }
  // {
  //   value: 5,
  //   label: '已删除'
  // }
]);
const columns = [
  {
    title: '发布人',
    key: 'releaseUserName',
    dataIndex: 'releaseUserName',
    width: '15%'
  },
  {
    title: '发布名称',
    key: 'infoName',
    dataIndex: 'infoName',
    ellipsis: true,
    width: '25%'
  },
  {
    title: '发布时间',
    key: 'createTime',
    dataIndex: 'createTime',
    width: '20%'
  },
  {
    title: '状态',
    key: 'infoState',
    dataIndex: 'infoState',
    width: '12%'
  },
  {
    title: '发布位置',
    key: 'equipmentTypeName',
    ellipsis: true,
    dataIndex: 'equipmentTypeName',
    width: '15%'
  },
  {
    title: '操作',
    key: 'operation',
    dataIndex: 'operation'
  }
];

const current = ref(1);
function onChange() {
  pageNum.value = current.value;
  onFinish();
}
function resetForm() {
  pageNum.value = 1;
  current.value = 1;
  formRef.value.resetFields();
  formState.startDate = '';
  formState.endDate = '';
  formState.infoState = '';
  formState.time = '';
  valueState.value = '';
  valuePosition.value = '';
  formState.publicName = '';
  deviceValue.value = '';
  pageSize.value = '10';
  onFinish();
}
// 发布状态下拉赋值
function showSearch(e, val) {
  pageNum.value = 1;
  current.value = 1;
  valueState.value = val?.value ?? '';
  formState.infoState = val?.value ?? '';
  onFinish();
}
function positionSearch(e, val) {
  pageNum.value = 1;
  current.value = 1;
  deviceValue.value = val?.value ?? '';
  valuePosition.value = val?.value ?? '';
  onFinish();
}

function query() {
  pageNum.value = 1;
  current.value = 1;
  onFinish();
}
</script>
<style lang="less" scoped>
@import './index.less';
</style>
